<?php

namespace app\middleware;

use think\{
    Request,
    Controller,
    Db,
    Session
};

class All
{
    public function handle($data)
    {
        if ($this->issuperadmin()) {
            return;
        }
        $authority = false;
        // $request = Request::instance();
        $request = $this->getRequest();
        $url = $request[0] . '/' . strtolower($request[1]);
        if ($url == 'admin/index' || $url == 'admin/login' || $url == 'admin/basic') {
            $authority = true;
        } else {
            $menu_id = Db::name('menu')->where('url', $url)->value('id');
            if ($menu_id) {
                $power_id = static::getPower($request[2]);
                $power_ids = Db::name('authority')->where('role_id', Session::get('user_info')['role_id'])->where('menu_id', $menu_id)->value('power_ids');
                if ($power_ids) {
                    $authority = in_array($power_id, explode(',', $power_ids));
                }
            }
        }
        $authority ?: $this->error();
    }

    private function issuperadmin()
    {
        return Session::get('user_info')['id'] == 1 ? true : false;
    }

    private function error()
    {
        $refClass = new \ReflectionClass('think\Controller');
        $instance = $refClass->newInstance();
        $method = $refClass->getMethod('error');
        $method->setAccessible(true);
        $method->invoke($instance, '你没有权限', '/admin/index/main.html');
    }

    private function getRequest(): array
    {
        // halt($_SERVER);
        $url = $_SERVER['PATH_INFO'];
        $url = str_replace([HTML_EXT], [''], $url);
        return explode('/', substr($url, 1));
    }

    private static function getPower($var): int
    {
        $power = 0;
        switch ($var) {
            case 'index':
                $power = 1;
                break;
            case 'add':
                $power = 2;
                break;
            case 'edit':
                $power = 3;
                break;
            case 'delete':
                $power = 4;
                break;
            case 'del':
                $power = 4;
                break;
            case 'shenhe':
                $power = 5;
                break;
            case 'fanshenhe':
                $power = 6;
                break;
            case 'daoru':
                $power = 7;
                break;
            case 'daochu':
                $power = 8;
                break;
            case 'qita':
                $power = 9;
                break;
            default:
                # code...
                break;
        }
        return $power;
    }
}
